package com.zhuqi.dynamic;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * Copyright (C) 2014-2016 天津紫藤科技有限公司. Co. Ltd. All Rights Reserved.
 *
 * @author LY
 * @date 2019/6/4
 */
public class SymmetricEncoder {

    private static final String CIPHER_MODE = "AES";

    /**
     * 加密
     * 1.构造密钥生成器
     * 2.根据ecnodeRules规则初始化密钥生成器
     * 3.产生密钥
     * 4.创建和初始化密码器
     * 5.内容加密
     * 6.返回字符串
     */
    public static String aesEncrypt(String encodeRules, String content) {
        try {

            //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
            //9.根据密码器的初始化方式--加密：将数据加密
            byte[] byteAes = getCipher(encodeRules, Cipher.ENCRYPT_MODE).doFinal(byteEncode);
            //10.将加密后的数据转换为字符串
            //这里用Base64Encoder中会找不到包
            //解决办法：
            //在项目的Build path中先移除JRE System Library，再添加库JRE System Library，重新编译后就一切正常了。
            //11.将字符串返回
            return Base64.getEncoder().encodeToString(new BASE64Encoder().encode(byteAes).getBytes());
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            return null;

        }
        //如果有错就返加nulll
    }


    /**
     * 解密
     * 解密过程：
     * 1.同加密1-4步
     * 2.将加密后的字符串反纺成byte[]数组
     * 3.将加密内容解密
     */
    public static String aesDecryptBank(String encodeRules, String content) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
        //8.将加密并编码后的内容解码成字节数组
        content = new String(Base64.getDecoder().decode(content), StandardCharsets.UTF_8);
        byte[] byteContent = new BASE64Decoder().decodeBuffer(content);
        byte[] byteDecode = getCipher(encodeRules, Cipher.DECRYPT_MODE).doFinal(byteContent);
        return new String(byteDecode, StandardCharsets.UTF_8);
    }


    private static Cipher getCipher(String encodeRules, int mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

        //1.构造密钥生成器，指定为AES算法,不区分大小写
        KeyGenerator keygen = KeyGenerator.getInstance(CIPHER_MODE);
        //2.根据ecnodeRules规则初始化密钥生成器
        //生成一个128位的随机源,根据传入的字节数组
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG") ;
        secureRandom.setSeed(encodeRules.getBytes());
        keygen.init(128, secureRandom);
//        keygen.init(128, new SecureRandom(encodeRules.getBytes()));
        //3.产生原始对称密钥
        SecretKey originalKey = keygen.generateKey();
        //4.获得原始对称密钥的字节数组
        byte[] raw = originalKey.getEncoded();
        //5.根据字节数组生成AES密钥
        SecretKey key = new SecretKeySpec(raw, CIPHER_MODE);
        //6.根据指定算法AES自成密码器
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
        cipher.init(mode, key);
        return cipher;
    }

    /**
     * 解密
     * 解密过程：
     * 1.同加密1-4步
     * 2.将加密后的字符串反纺成byte[]数组
     * 3.将加密内容解密
     */
    public static String aesDecrypt(String encodeRules, String content) {
        try {
            //8.将加密并编码后的内容解码成字节数组
            content = new String(Base64.getDecoder().decode(content), StandardCharsets.UTF_8);
            byte[] byteContent = new BASE64Decoder().decodeBuffer(content);
            byte[] byteDecode = getCipher(encodeRules, Cipher.DECRYPT_MODE).doFinal(byteContent);
            return new String(byteDecode, StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException | IllegalBlockSizeException | BadPaddingException e) {
            //log.error(e.getMessage(),e);
            return null;
        }
        //如果有错就返加nulll
    }

//    public static void main(String[] args) {
////        Scanner scanner = new Scanner(System.in);
////        /*
////         * 加密
////         */
////        System.out.println("使用AES对称加密，请输入加密的规则");
////        String encodeRules = scanner.next();
////        System.out.println("请输入要加密的内容:");
////        String content = scanner.next();
////        System.out.println("根据输入的规则" + encodeRules + "加密后的密文是:" + aesEncrypt(encodeRules, content));
////
////        /*
////         * 解密
////         */
////        System.out.println("使用AES对称解密，请输入加密的规则：(须与加密相同)");
////        encodeRules = scanner.next();
////        System.out.println("请输入要解密的内容（密文）:");
////        content = scanner.next();
////        System.out.println("根据输入的规则" + encodeRules + "解密后的明文是:" + aesDecrypt(encodeRules, content));
////        Map<String, Object> param = SignTools.getTreeMap();
////        param.put("a", "a");
////        param.put("b", "a");
////        param.put("c", "a");
////        param.put("q", "a");
////        param.put("j", "a");
////        param.put("e", "a");
////        param.put("d", "a");
////        String jsonString = JSON.toJSONString(param);
////        String encrypt = SymmetricEncoder.aesEncrypt("TOLIVEWOULDBEANAWFULLYBIGADVENTURE", jsonString);
////        System.out.println(encrypt);
////        Map<String, Object> requestMap = new HashMap<>(16);
////        requestMap.put("jsonDataStr", encrypt);
////        HttpClientUtil.httpPostRequest("接口地址", requestMap);
//    }

}

